package com.gorkr.labuladong.data_struct.array;

import org.junit.jupiter.api.Test;

import java.util.Objects;

/**
 * 最长公共前缀
 * @author gorkr
 * @date 2022/07/25 16:38
 **/
public class E14LongestCommonPrefix {

    public String longestCommonPrefix(String[] strs) {
        if(strs.length<2){
            return strs[0];
        }
        for (int i = 0; i < strs.length; i++) {
            if(Objects.equals(strs[i], "")){
                return "";
            }

        }


        int res = 0;

        while (true){
            for (int i = 1; i < strs.length; i++) {

                if (strs[0].length()-1<res ||strs[i].length()-1<res ||  strs[0].charAt(res)!=strs[i].charAt(res)) {
                    return  strs[0].substring(0,res);
                }
            }
            res++;
        }
    }
    public String longestCommonPrefix2(String[] strs) {
        if(strs.length<1){
            return "";
        }
        String prefix = strs[0];
        for (int i = 0; i < strs.length; i++) {
            if(prefix.length()==0){
                return "";
            }
            while (strs[i].indexOf(prefix)!=0){
                prefix = prefix.substring(0,prefix.length()-1);
            }

        }
        return prefix;
    }


    @Test
    public void test(){
        String[] strs = {"c","acc","ccc"};
        System.out.println(longestCommonPrefix2(strs));
    }

}
    